package com.swf.jpa.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.StringWriter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.swf.jpa.framework.constant.MockConstants;
import com.swf.jpa.framework.constant.MockEnum;

public class MockUtils {
	private static final Log logger = LogFactory.getLog(MockUtils.class);
	public static String formatDate(Date date,String pattern){
		SimpleDateFormat  dateFormat = new SimpleDateFormat (pattern);
		return dateFormat.format(date);
	}
	public static String today(){
		Date date = new Date();
		return formatDate(date,"yyyyMMdd");
	}
	public static String currentTime(){
		Date date = new Date();
		return formatDate(date,"yyyyMMddHHmmss");
	}
	
	  /**
     * 将报文键值对转换为xml报文
     * @param formatMap 报文键值对
     * @param charset 字符集
     * @return
     */
    public static String printFormat(Map<String,String> formatMap,String rootName,String charset){
    	Document doc = new Document();
    	Element root = new Element(rootName);
    	doc.setRootElement(root);
    	String name;
    	String text;
    	Element element;
    	for (Map.Entry<String, String> entry:formatMap.entrySet()){
    		name = entry.getKey();
    		text = entry.getValue();
    		element = new Element(name);
    		element.setText(text);
    		root.addContent(element);
    	}
    	XMLOutputter out = new XMLOutputter();
    	out.setFormat(Format.getCompactFormat().setEncoding(charset));  
    	return out.outputString(doc);
    }
    
    public static String trimToEmpty(String str){
    	return trimToEmpty(str, "");
    }
    public static String trimToEmpty(String str,String defaultValue){
    	if (str==null){
    		str=defaultValue;
    	}else{
    		str = str.trim();
    	}
    	return str;
    }
    public static String trimToEmpty(Object str){
    	if (str==null){
    		return "";
    	}
    	return trimToEmpty((String)str);
    }
    
    
    @SuppressWarnings("unchecked")
    public static Map<String,String> getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map<String,String> returnMap = new HashMap<String,String>();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }
    
    
    public static void setAttribute(HttpServletRequest request,MockEnum e,Object o){
    	request.setAttribute(e.name(), o);
    }
    public static Object getAttribute(HttpServletRequest request,MockEnum e){
    	return request.getAttribute(e.name());
    }
    public static <T> T getAttribute(HttpServletRequest request,MockEnum e,Class<T> requiredType){
    	return (T)request.getAttribute(e.name());
    }
    
    /**
     * 改变字符集
     * @param charset
     */
    public static void changeCharset(String charset){
    	logger.debug(String.format("change charset from %s to %s", MockConstants.CURRENT_CHARSET,charset));
    	MockConstants.CURRENT_CHARSET = charset;
    }
    
    /**
     * 如果文件父目录不存在，创建父目录
     * @param file 文件
     * @return
     */
    public static boolean createParentDir(File file){
    	File parent = file.getParentFile();
    	if (!parent.exists()){
    		return parent.mkdirs();
    	}
    	return true;
    }
    
    
    public static Class<?> getTypeFormList(java.lang.reflect.Field field){
    	Type type = field.getGenericType(); 
		if (type instanceof ParameterizedType) {     
		   ParameterizedType paramType = (ParameterizedType) type;     
		   Type[] actualTypes = paramType.getActualTypeArguments();  
		   return  (Class<?>)actualTypes[0];
		}
		return Object.class;
    }
    
    public static String readLines(File file, String charset,int startLine,int endLine,String lineSeparator) throws IOException {
		LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file),charset));
		String currentLine;
		StringBuffer content = new StringBuffer();
		while ((currentLine = reader.readLine()) != null){
			int currentLineNumber = reader.getLineNumber();
			if (currentLineNumber>=startLine&&currentLineNumber<=endLine){
				content.append(currentLine);
				if (currentLineNumber!=endLine){
					content.append(lineSeparator);
				}
			}
		}
		reader.close();
		return  content.toString();
	}
    
    
    public static <T> String formatBalance(T balance,String pattern){
    	DecimalFormat df = new DecimalFormat(pattern);
    	return df.format(balance);
    }
    
    
}
